﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using bmapi.HelperClass;
using bmapi.Models.DataEntity;
using bmapi.SQLServerAccess;

namespace bmapi.Controllers
{
    public class CADStyleController : CADApplyController
    {
        [HttpPost,Route("cadStyle/Apply")]
        public string Apply()
        {
            //登陆者login_id
            //id实际是token 
            User user = GetUserByLoginID(GetCrrentIDByToken());
            if (user != null)
            {
                if (user.code .Equals(35))
                {
                    PidOid pod = LockPod(user);
                    if (pod == null)
                        return ReturnOK(0, 0, "", 0);//没有合适任务
                    else
                    {
                        /*PC pc = null; *///需要联合查询
                        return ReturnOK(pod.OrderId, 35, pod.PcName, pod.Pod);
                    }
                }
                else
                {
                    PC pc = LockTask(user);
                    if (pc == null)
                        return ReturnOK(0, 0, "");//没有合适任务
                    else
                    {
                        AddTask(user.code, pc.pc_id);
                        return ReturnOK(pc.pc_id, pc.step, pc.path);
                    }
                }
                //return ReturnError(201, "不能处理的工序");
            }
            else
            {
                return ReturnError(201, "不合法的用户");
            }
        }
        /// <summary>
        /// 寻找待分配的特体检查任务
        /// </summary>
        /// <param name="u"></param>
        /// <param name="code"></param>
        protected PidOid LockPod(User u)
        {
            PidOid pod = null;
            for (int i = 0; i < 5; i++)
            {
                string sql = "select top 1 pod_id as PodId,Pod_tb.Pod,PC_tb.pc_id as OrderId,PC_tb.path as PcName from Pod_tb join PC_tb on Pod_tb.order_id=PC_tb.pc_id where user_id=0 and PC_tb.PLID=@plid order by time desc";
                SQLCommand sc = new SQLCommand(sql, "@plid", u.PLID);
                DataRow dr = sc.ExecuteOneRow();
                if (dr == null)
                {
                    break;
                }
                else
                {
                    pod = AssistFun.DataRowToObject<PidOid>(dr);                    
                    //有特体任务修改pod  user_id=当前loginid 
                    sql = "update Pod_tb set user_id=@uid where pod_id=@pid and user_id=0";
                    sc = new SQLCommand(sql);
                    sc.Add("@uid", u.login_id);
                    sc.Add("@pid", pod.PodId);
                    int rtn = sc.ExecuteNonQuery();
                    if (rtn == 1)
                        return pod;                   
                }
            }
            WriteDebug("LockPod", "没有特体检查任务");
            return pod;
        }
    }
}
